// 语音识别 文字转语音
let config = {
	secretKey: 'VCgv1sUs11mKdhX8VeicHitqZ5PVMzOY',
	secretId: 'AKID97qLcfl0JL8fy3uWv62jGZeU5S5WalbC',
	appId: 1251133427,
}

import {
	store
} from "../store/index.js"
/** 获取签名 start */
const toUint8Array = (wordArray) => {
	// Shortcuts
	const words = wordArray.words;
	const sigBytes = wordArray.sigBytes;

	// Convert
	const u8 = new Uint8Array(sigBytes);
	for (let i = 0; i < sigBytes; i++) {
		u8[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
	}
	return u8;
}

const Uint8ArrayToString = (fileData) => {
	let dataString = '';
	for (let i = 0; i < fileData.length; i++) {
		dataString += String.fromCharCode(fileData[i]);
	}
	return dataString;
}
// 签名函数示例
const signCallback = (signStr) => {
	const secretKey = config.secretKey;
	const hash = window.CryptoJSTest.HmacSHA1(signStr, secretKey);
	const bytes = Uint8ArrayToString(toUint8Array(hash));
	return window.btoa(bytes);
}

/** 获取签名 end */

const params = {
	signCallback: signCallback, // 鉴权函数，若直接使用默认鉴权函数。可不传此参数
	// 用户参数
	secretid: config.secretId,
	secretkey: config.secretKey,
	appid: config.appId,
	engine_model_type: '16k_zh', // 因为内置WebRecorder采样16k的数据，所以参数 engineModelType 需要选择16k的引擎，为 '16k_zh'
}
let webAudioSpeechRecognizer;
let isCanStop;

export const kaishi = async (callback) => {

	webAudioSpeechRecognizer = new WebAudioSpeechRecognizer(params);
	store.state.xiaoxinr = ""
	webAudioSpeechRecognizer.start();

	// 开始识别
	webAudioSpeechRecognizer.OnRecognitionStart = (res) => {
		console.log('开始识别', res);
		webAudioSpeechRecognizer.start();
	};
	// 一句话开始
	webAudioSpeechRecognizer.OnSentenceBegin = (res) => {

		console.log('一句话开始', res);
		isCanStop = true;
	};
	// 识别变化时
	webAudioSpeechRecognizer.OnRecognitionResultChange = (res) => {
		store.state.isanzhu = true
		console.log('识别变化时', res);
	};
	// 一句话结束
	webAudioSpeechRecognizer.OnSentenceEnd = (res) => {

		store.state.xiaoxinr = res.result.voice_text_str;
		console.log('一句话结束', store.state.xiaoxinr);
		store.state.isanzhu = false
		callback()

	};
	// 识别结束
	webAudioSpeechRecognizer.OnRecognitionComplete = (res) => {
		console.log('识别结束', res);
		store.state.isanzhu = false
	};
	// 识别错误
	webAudioSpeechRecognizer.OnError = (res) => {
		console.log('识别失败', res)
		store.state.isanzhu = false
	};

}

export const tingzhi = () => {
	try {
		webAudioSpeechRecognizer.stop();
	} catch (e) {

	}
}